<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="部门名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
        <el-form-item>
					<el-button type="primary" @click="handleDistribution">分配</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="clue" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="fullName" label="名字" width="120" sortable>
			</el-table-column>
			<el-table-column prop="company" label="公司" width="100" sortable>
			</el-table-column>
			<el-table-column prop="job" label="工作" width="100" sortable>
			</el-table-column>
      <el-table-column prop="email" label="邮箱" width="100" sortable>
			</el-table-column>
      <el-table-column prop="phone" label="电话" width="100" sortable>
			</el-table-column>
			<el-table-column prop="employee.username" label="营销人员" width="120" sortable>
			</el-table-column>
      <el-table-column prop="state" label="状态" width="120" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.state == 1" style="color: gold">跟进中</span>
          <span v-if="scope.row.state == -1" style="color: darkred">放入线索池</span>
          <span v-if="scope.row.state == 2" style="color: greenyellow">已转化为商机</span>
          <span v-if="scope.row.state == 0" style="color: red">未分配</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="120" sortable>
      </el-table-column>
      <el-table-column prop="nextContactTime" label="跟进时间" width="120" sortable>
      </el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleActivity(scope.$index, scope.row)">关联活动</el-button>
					<el-button type="danger" size="small" @click="handleBusiness(scope.$index, scope.row)">转为商机</el-button>
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          layout="prev, pager, next"
          :current-page="query.page"
          @current-change="handleCurrentChange"
          :page-size="query.pageSize"
          :total="query.total"
          style="float:right;">
      </el-pagination>
    </el-col>
		<!--新增/修改界面-->
		<el-dialog title="新增/修改" :visible.sync="clueFormVisible" :close-on-click-modal="false">
			<el-form :model="clueForm" label-width="80px" :rules="clueFormRules" ref="clueForm">
				<el-form-item label="部门名" prop="name">
					<el-input v-model="clueForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="父部门">
          <el-cascader v-model="clueForm.parent"
                       :options="clueTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item label="管理人员">
          <el-select v-model="clueForm.employee" clearable value-key="id" placeholder="请选择">

            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" >
<!--          <el-input v-model="clueForm.state" auto-complete="off"></el-input>-->
            <el-radio-group v-model="clueForm.state">
              <el-radio class="radio" :label="1">正常</el-radio>
              <el-radio class="radio" :label="0">禁用</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="部门简介" prop="intro">
          <el-input type="textarea" v-model="clueForm.intro" auto-complete="off">
          </el-input>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="clueFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="save" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
    <el-dialog title="分配线索" :visible.sync="clueAssignFormVisible" :close-on-click-modal="false">
      <el-form :model="clueForm" label-width="80px" :rules="clueFormRules" ref="clueActivity">
        <el-form-item label="名称" prop="name">
          <el-input v-model="clueForm.fullName" disabled auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="name">
          <el-input v-model="clueForm.phone" disabled auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="营销人员">
          <el-select v-model="clueForm.employee" clearable value-key="id" placeholder="请选择">
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native=" clueAssignFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="clueAssignSave" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog title="商机转化" :visible.sync="clueBusinessVisible" :close-on-click-modal="false">
      <el-form :model="busniessData" label-width="80px" :rules="clueFormRules" ref="clueActivity">
        <el-form-item label="名称" prop="name">
          <el-input v-model="busniessData.clue.fullName" disabled auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="name">
          <el-input v-model="busniessData.clue.phone" disabled auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="产品">
          <el-select v-model="busniessData.product" clearable value-key="id" placeholder="请选择">
            <el-option
                v-for="item in products"
                :key="item.id"
                :label="item.name"
                :value="item">
              <span style="float: left">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native=" clueBusinessVisible = false">取消</el-button>
        <el-button type="primary" @click.native="clueBusniessSave" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
		<el-dialog title="关联活动" :visible.sync="clueActivityFormVisible" :close-on-click-modal="false">
			<el-form :model="clueActivity" label-width="80px" ref="clueForm">
				<el-form-item >
          <el-checkbox-group v-model="clueActivity.activityIds">
            <el-checkbox v-for="a in activitys"
                         :label="a.id" >{{a.name}}</el-checkbox>
          </el-checkbox-group>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="clueActivityFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveActivity" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>

  </section>
</template>

<script>
	export default {
		data() {
			return {
			  //转化商机数据
        busniessData:{
          clue:{
            id:null,
            fullName: '',
            phone:'',
            employee:{
              id:null,
              name:"",
            }
          },
          product:{
            id:null,
            name:"",
            price:''
          }
        },
			  //分页
				query: {
				pageSize:10,
				page: 1,
				total: 0,
        keyword:''
				},
        employees:[],
        activitys:[],
				clue: [],
        clueTree:[],
				listLoading: false,
				sels: [],//列表选中列

				clueFormVisible: false,//弹出框界面是否显示
				clueActivityFormVisible: false,//弹出框界面是否显示
				clueAssignFormVisible: false,//弹出框界面是否显示
        clueBusinessVisible:false,
				addLoading: false,
				clueFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//新增界面数据->shuju
				clueForm: {
				  id:null,
          fullName: '',
          company:'',
          job:'',
          email:'',
          phone:'',
          state:null,
          createTime:"",
          nextContactTime:'',
          employee: {
					  id:null,
            username:''
          },
				},
        //关联活动数据
        clueActivity:{
          clueId:null,
          activityIds:[]
        },
        products:[]
			}
		},
		methods: {
		  //获取所有的产品信息
      getProducts(){
        this.$http.get("/product")
                  .then(result =>{
                    result = result.data
                    // console.log(result)
                    if(result.success){
                      this.products = result.result;
                    }
                  }).catch(result =>{
                      this.$message({  message: '获取产品列表失败'+result.data.message, type: 'error' });
        })
      },
		  //保存线索转化商机
      clueBusniessSave(){
        this.$confirm('确认提交吗？', '提示', {})
            .then(() => {
              this.addLoading = true;
              this.$http.post("/clue/business",this.busniessData)
                  .then((result) => {
                    result = result.data;
                    if(result.success){
                      this.$message({  message: '提交成功', type: 'success' });
                      //成功以后要关闭模态框并刷新数据
                      this.addLoading = false;
                      this.clueBusinessVisible = false;
                      this.query.page = 1;
                      this.getClues();
                    }else {
                      this.$message({  message: '提交失败'+result.message, type: 'success' });
                    }
                  })
            }).catch(() => {
          this.$message({message: '已取消', type: 'info'
          });
        });

      },
      //弹出框
      handleBusiness(index,row){
        this.clueBusinessVisible = true;
        this.getProducts();
        this.busniessData.clue = row;

      },
		  //获取活动列表
      getActivity(){
        this.$http.get("/activity")
                  .then((res) => {
                    res = res.data;
                    // console.log(res);
                    if(res.success){
                      this.query.total = res.result.total;
                      this.activitys = res.result;
                    }
                  })
      },
		  //给线索分配跟进人员
      handleDistribution(){
        this.clueAssignFormVisible = true;
        if(this.sels.length != 1){
        this.clueAssignFormVisible = false;
          this.$message({message: '请选择一条线索后再进行分配', type: 'error'});
          return;
        }
        this.clueForm = this.sels[0]
        //clueForm里面的值没有进行连表查询,所以employee和parent的值是单独的属性,不是对象
        this.getEmployees();
      },
      //保存线索
      clueAssignSave(){
        this.$confirm('确认提交吗？', '提示', {})
            .then(() => {
              this.addLoading = true;
              console.log("往后端传的clue"+this.clueForm)
              this.$http.post("/clue/assign",this.clueForm)
                  .then((result) => {
                    result = result.data;
                    if(result.success){
                      this.$message({  message: '提交成功', type: 'success' });
                      //成功以后要关闭模态框并刷新数据
                      this.addLoading = false;
                      this.clueAssignFormVisible = false;
                      this.query.page = 1;
                      this.getClues();
                    }else {
                      this.$message({  message: '提交失败'+result.message, type: 'success' });
                    }
                  })
            }).catch(() => {
          this.$message({message: '已取消', type: 'info'
          });
        });

      },
		  //设置关联活动
      handleActivity(index,row){
        //点击以后就查询所有的活动信息
        this.getActivity();
        this.clueActivity.clueId = row.id
        this.clueActivityFormVisible = true;


      },
      //保存关联活动
      saveActivity(){
        this.$confirm('确认提交吗？', '提示', {})
            .then(() => {
              this.addLoading = true;
              console.log(this.clueActivity)

              this.$http.post("/clueActivity/save",this.clueActivity)
                  .then((result) => {
                    result = result.data;
                    if(result.success){
                      this.$message({  message: '提交成功', type: 'success' });
                      //成功以后要关闭模态框并刷新数据
                      this.addLoading = false;
                      this.clueActivityFormVisible = false;
                      this.query.page = 1;
                      this.getClues();
                    }else {
                      this.$message({  message: '提交失败'+result.message, type: 'success' });
                    }
                  })
            }).catch(() => {
          this.$message({message: '已取消', type: 'info'
          });
        });
      },
      //高级查询
      search(){
        this.query.page = 1
        this.getClues();
      },
      handleCurrentChange(val){
        this.query.page = val;
        this.getClues()
      },
      //获取员工列表
      getEmployees(){
        //NProgress.start();
        this.$http.get("/employee")
            .then((res) => {
              res = res.data;
              console.log(res);
              if(res.success){
                this.query.total = res.result.total;
                this.employees = res.result;

              }
            });
      },

			//获取线索列表
			getClues() {
				this.listLoading = true;
       this.$http.post("/clue",this.query)
           .then((res) => {
             console.log(this.query.keyword)
             res = res.data;
            console.log(res);
            if(res.success){
            this.query.total = res.result.total;
            this.clue = res.result.datas;
            // console.log(this.clue)

            }
            this.listLoading = false;
				});
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
          this.$http.delete("/clue/"+row.id)
                    .then(result=>{
                      result = result.data;
                      if(result.success){
                        this.$message({ message: '删除成功', type: 'success' });
                        this.query.page = 1;
                        this.addLoading = false;
                        this.getClues();
                      }else{
                        this.$message({ message: '删除失败'+result.message, type: 'erro' });
                      }
                    })

				}).catch(() => {
          this.$message({ message: '已取消删除', type: 'info' });
				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
        // this.getEmployees();
        this.clueFormVisible = true;
				this.clueForm = Object.assign({}, row);
        //clueForm里面的值没有进行连表查询,所以employee和parent的值是单独的属性,不是对象
        if(this.clueForm.employee == null){
          this.clueForm.employee={
            id:null
          };
        }
        //父级部门回显
        if(row.path != null){//path不等于空的时候->拿到他然后根据/分割
          let arrays = row.path.split("/");//分割以后是个数组,且字符串模式
          let ids = [];
          for (let i = 1;i < arrays.length-1;i++){
            ids.push(parseInt(arrays[i]));//往数组里面放值
          }
          this.clueForm.parent = ids
        }
			},
			//显示新增界面
			handleAdd: function () {
				this.clueFormVisible = true;
				this.clueForm = {
          id:null,
          fullName: '',
          company:'',
          job:'',
          email:'',
          phone:'',
          state:null,
          createTime:"",
          nextContactTime:'',
          employee: {
            id:null,
            username:''
          }
        };
				this.getEmployees();
			},
			//新增
      save: function () {
        this.$confirm('确认提交吗？', '提示', {})
            .then(() => {
              this.addLoading = true;
              //NProgress.start();
              let para = Object.assign({}, this.clueForm);
              //对parent进行一个判空,如果不为空的话需要将数据进行一个转化->部门下拉框
              if(para.parent != null){
                let array = para.parent;
                //在path中最后一个id才是他相应的父级部门
                para.parent = {id:array[array.length-1]};
              }
              this.$http.put("/clue",para)
                  .then((result) => {
                    result = result.data;
                    if(result.success){
                      this.$message({  message: '提交成功', type: 'success' });
                      //成功以后要关闭模态框并刷新数据
                      this.addLoading = false;
                      this.clueFormVisible = false;
                      this.query.page = 1;
                      this.getClues();
                    }else {
                      this.$message({  message: '提交失败'+result.message, type: 'success' });
                    }
                  })
            }).catch(() => {
          this.$message({message: '已取消删除', type: 'info'
          });
        });

			},
			selsChange: function (sels) {

				this.sels = sels;//获取整行数据
        console.log(this.sels)
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
				// console.log("ids:"+ids)
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					// let para = { ids: ids };
					this.$http.patch("/clue",ids).then((res) => {
						this.listLoading = false;
						if(res.data.success){
						this.$message({ message: '删除成功', type: 'success' });

            }else {
              this.$message({ message: '删除失败'+res.data.message, type: 'error' });
            }
						//NProgress.done();
            this.query.page = 1;
						this.getClues();
					});
				}).catch(() => {
          this.$message({ message: '已取消删除', type: 'info' });
				});
			}
		},
		mounted() {
			this.getClues();
			this.getActivity();
		}
	}

</script>

<style scoped>

</style>